package com.sunhao.myapplication;

import android.app.Application;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.sunhao.myapplication.database.ShoppingDBHelper;
import com.sunhao.myapplication.entity.GoodsInfo;
import com.sunhao.myapplication.utils.FileUtil;
import com.sunhao.myapplication.utils.SharedUtil;

import java.io.File;
import java.util.ArrayList;

public class MyApplication extends Application {

    //app启动时调用
    @Override
    public void onCreate() {
        super.onCreate();

        //对商品信息进行初始化
        initGoodsInfo();
    }

    //第一次打开才需要执行的操作
    private void initGoodsInfo() {
        boolean isFirst = SharedUtil.getInstance(this).readBoolean("first", true);
        String directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.separator;
        if (isFirst) {

            //模拟网络图片下载
            ArrayList<GoodsInfo> list = GoodsInfo.getDefaultList();
            for (GoodsInfo info : list) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), info.pic);
                String path = directory + info.id + ".jpg";
                //往存储卡保存商品图片
                FileUtil.saveImage(path, bitmap);
                //回收位图对象
                bitmap.recycle();
                info.picPath = path;
            }

            //打开数据库,插入数据
            ShoppingDBHelper dbHelper = ShoppingDBHelper.getInstance(this);
            dbHelper.openWriteLink();
            dbHelper.insertGoodsInfo(list);
            dbHelper.closeLink();

            //操作完成后,将first改为false
            //下次不再进行插入数据操作
            SharedUtil.getInstance(this).writeBoolean("first", false);
        }
    }


    //app终止时调用
    @Override
    public void onTerminate() {
        super.onTerminate();
    }


    //配置改变时,如横屏变为竖屏
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
